<template>
  <div class="container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">宠物信息管理系统</h1>
	            <p class="sub-title">每一只宠物的登记信息，都是对公共安全的负责；每一次养宠行为的引导，都是对社区文明的守护，让爱宠与文明同行</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 查询区域 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="16">
        <el-form inline :model="searchForm" class="search-form">
          <el-form-item label="主人名称">
            <el-input 
              v-model="searchForm.owner" 
              placeholder="请输入主人名称"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryByOwner">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8" class="text-right">
        <el-button type="primary" @click="openAddDialog">添加宠物</el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-row>
      <el-table
        :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)"
        border
        style="width: 100%"
        height="450">
        <el-table-column 
          prop="id" 
          label="宠物ID" 
          width="100" 
          align="center">
        </el-table-column>
        <el-table-column 
          prop="petName" 
          label="宠物名称" 
          width="150" 
          align="center">
        </el-table-column>
        <el-table-column 
          prop="petBreed" 
          label="宠物品种" 
          width="150" 
          align="center">
        </el-table-column>
        <el-table-column 
          prop="owner" 
          label="主人姓名" 
          width="150" 
          align="center">
        </el-table-column>
        <el-table-column 
          prop="createdAt" 
          label="创建时间" 
          align="center">
        </el-table-column>
        <el-table-column 
          prop="selectedImageUrl" 
          label="宠物图片" 
          width="200" 
          align="center">
          <template #default="scope">
            <el-image 
              v-if="scope.row.selectedImageUrl"
              :src="scope.row.selectedImageUrl" 
              :preview-src-list="[scope.row.selectedImageUrl]"
              style="width: 50px; height: 50px; object-fit: cover">
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button size="small" type="success" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 10px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]"
          :page-size="pageSize"
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </el-row>
    </el-row>

    <!-- 添加对话框 -->
    <el-dialog 
      title="添加宠物" 
      v-model="addDialogVisible" 
      width="50%">
      <el-form 
        :model="addForm" 
        ref="addFormRef" 
        :rules="rules" 
        label-width="120px">
        <el-form-item label="宠物名称" prop="petName">
          <el-input v-model="addForm.petName" placeholder="请输入宠物名称"></el-input>
        </el-form-item>
        <el-form-item label="宠物品种" prop="petBreed">
          <el-input v-model="addForm.petBreed" placeholder="请输入宠物品种"></el-input>
        </el-form-item>
        <el-form-item label="主人姓名" prop="owner">
          <el-input v-model="addForm.owner" placeholder="请输入主人姓名"></el-input>
        </el-form-item>
        <el-form-item label="宠物图片URL">
          <el-input v-model="addForm.selectedImageUrl" placeholder="请输入图片URL地址"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog 
      title="编辑宠物" 
      v-model="editDialogVisible" 
      width="50%">
      <el-form 
        :model="editForm" 
        ref="editFormRef" 
        :rules="rules" 
        label-width="120px">
        <el-form-item label="宠物ID" prop="id">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="宠物名称" prop="petName">
          <el-input v-model="editForm.petName" placeholder="请输入宠物名称"></el-input>
        </el-form-item>
        <el-form-item label="宠物品种" prop="petBreed">
          <el-input v-model="editForm.petBreed" placeholder="请输入宠物品种"></el-input>
        </el-form-item>
        <el-form-item label="主人姓名" prop="owner">
          <el-input v-model="editForm.owner" placeholder="请输入主人姓名"></el-input>
        </el-form-item>
        <el-form-item label="宠物图片URL">
          <el-input v-model="editForm.selectedImageUrl" placeholder="请输入图片URL地址"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 假设 axios 相关请求方法在 utils/axios.js 中，需根据实际路径调整
import { post, get } from '@/utils/axios.js'

// 表格数据与分页
const currentPage = ref(1)
const pageSize = ref(5)
const tableData = ref([])

// 查询表单
const searchForm = reactive({
  owner: ''
})

// 添加对话框相关
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  petName: '',
  petBreed: '',
  owner: '',
  selectedImageUrl: ''
})

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: '',
  petName: '',
  petBreed: '',
  owner: '',
  selectedImageUrl: ''
})

// 表单验证规则
const rules = {
  petName: [
    { required: true, message: '请输入宠物名称', trigger: 'blur' }
  ],
  owner: [
    { required: true, message: '请输入主人姓名', trigger: 'blur' }
  ]
}

// 分页方法
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1 // 重置为第一页，保持分页逻辑一致性
}

function handleCurrentChange(val) {
  currentPage.value = val
}

// 获取所有宠物数据
function getAllPets() {
  get('/api/pets/getAll', {}, (res) => {
    if (res.status === 1) {
      tableData.value = res.data
    } else {
      ElMessage.error('未查询到数据')
      tableData.value = []
    }
  })
}

// 按主人查询 - 修复了字符串判断错误
function queryByOwner() {
  // 修复：使用 length 判断字符串是否为空，而不是 isEmpty() 方法
  if (!searchForm.owner || searchForm.owner.trim().length === 0) {
    ElMessage.warning('请输入主人名称')
    return
  }
  
  const params = {
    owner: searchForm.owner.trim()
  }
  
  get('/api/pets/getByOwner', params, (res) => {
    if (res.status === 1) {
      tableData.value = res.data
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(res.msg || '查询失败')
    }
  })
}

// 重置查询
function resetSearch() {
  searchForm.owner = ''
  getAllPets()
}

// 打开添加对话框
function openAddDialog() {
  // 重置表单数据
  addForm.petName = ''
  addForm.petBreed = ''
  addForm.owner = ''
  addForm.selectedImageUrl = ''
  
  addDialogVisible.value = true
  
  // 下一次DOM更新后清除验证状态
  nextTick(() => {
    if (addFormRef.value) {
      addFormRef.value.clearValidate()
    }
  })
}

// 处理添加
function handleAdd() {
  addFormRef.value.validate((valid) => {
    if (valid) {
      post('/api/pets/add', addForm, (res) => {
        if (res.status === 1) {
          ElMessage.success('添加成功')
          addDialogVisible.value = false
          getAllPets()
        } else {
          ElMessage.error(res.msg || '添加失败')
        }
      })
    }
  })
}

// 打开编辑对话框
function openEditDialog(row) {
  // 复制行数据到编辑表单
  editForm.id = row.id
  editForm.petName = row.petName
  editForm.petBreed = row.petBreed
  editForm.owner = row.owner
  editForm.selectedImageUrl = row.selectedImageUrl
  
  editDialogVisible.value = true
  
  // 下一次DOM更新后清除验证状态
  nextTick(() => {
    if (editFormRef.value) {
      editFormRef.value.clearValidate()
    }
  })
}

// 处理更新
function handleUpdate() {
  editFormRef.value.validate((valid) => {
    if (valid) {
      post('/api/pets/updateById', editForm, (res) => {
        if (res.status === 1) {
          ElMessage.success('更新成功')
          editDialogVisible.value = false
          getAllPets()
        } else {
          ElMessage.error(res.msg || '更新失败')
        }
      })
    }
  })
}

// 处理删除
function handleDelete(id) {
  ElMessageBox.confirm(
    `确定要删除ID为【${id}】的宠物记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    get('/api/pets/deleteById', { id }, (res) => {
      if (res.status === 1) {
        ElMessage.success('删除成功')
        getAllPets()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    // 取消删除，不做额外操作
  })
}

// 页面加载时获取所有数据
onMounted(() => {
  getAllPets()
})
</script>

<style scoped>
.container {
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.search-form {
  margin-bottom: 0;
}

.text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 对话框内容区滚动优化 */
.el-dialog__body {
  max-height: 500px;
  overflow-y: auto;
}
</style>
